package com.projectzqjz.parttimework.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.projectzqjz.parttimework.App;
import com.projectzqjz.parttimework.R;
import com.projectzqjz.parttimework.adapter.PartApplyAdapter;
import com.projectzqjz.parttimework.base.BaseActivity;
import com.projectzqjz.parttimework.entity.DailyEntity;
import com.projectzqjz.parttimework.entity.PartBaseEntity;
import com.projectzqjz.parttimework.myinterface.myLocation;
import com.projectzqjz.parttimework.net.MyCallback;
import com.projectzqjz.parttimework.net.NoValidationTask;
import com.projectzqjz.parttimework.utils.GPSUtils;
import com.projectzqjz.parttimework.utils.NewsToastUtils;
import com.projectzqjz.parttimework.utils.PermissionUtils;
import com.projectzqjz.parttimework.utils.ScreenUtil;
import com.projectzqjz.parttimework.utils.TitleBuilder;
import com.projectzqjz.putorefresh.BaseBothListener;
import com.projectzqjz.putorefresh.PullToBothLayout;
import com.projectzqjz.putorefresh.ViewStatus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class PartCategoriesActivity extends BaseActivity {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.pullRefresh)
    PullToBothLayout pullToBothLayout;
    private PartApplyAdapter dailyAdapter = null;
    private List<DailyEntity> list = new ArrayList<>();
    @BindView(R.id.tv_last)
    TextView tvLast;
    @BindView(R.id.tv_zq)
    TextView tvZq;
    @BindView(R.id.tv_high)
    TextView tvHigh;
    @BindView(R.id.tv_near)
    TextView tvNear;

    @BindView(R.id.line_1)
    TextView line_1;
    @BindView(R.id.line_2)
    TextView line_2;
    @BindView(R.id.line_3)
    TextView line_3;
    @BindView(R.id.line_4)
    TextView line_4;

    private int page = 1;
    private boolean isRefresh = true;

    private String type = "0";//获取类型
    private boolean isLast = false;//是否是最后一项
    private List<TextView> tvList = new ArrayList<>();//存放title按钮
    private List<View> lineList = new ArrayList<>();//存放下划线
    private String city = "";

    @Override
    public void setListen() {
        pullToBothLayout.setRefreshListener(new BaseBothListener() {
            @Override
            public void refresh() {
                page = 1;
                isRefresh = true;
                if (isLast) {
                    getJobList2();
                } else {
                    getJobList();
                }
            }

            @Override
            public void loadMore() {
                page++;
                isRefresh = false;
                if (isLast) {
                    getJobList2();
                } else {
                    getJobList();
                }
            }
        });
    }

    //关闭下拉刷新
    private void closePullTo() {
        pullToBothLayout.finishRefresh();
        pullToBothLayout.finishLoadMore();
    }

    /**
     * 获取定位权限
     */
    private void getLocationPermission() {
        int flag = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        if (flag != PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            getLocation();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults[0] == PERMISSION_GRANTED) {
                getLocation();
            } else {
                NewsToastUtils.showToast(App.getContext(), "权限被拒绝！");
                pullToBothLayout.showView(ViewStatus.ERROR_STATUS);
                pullToBothLayout.getView(ViewStatus.ERROR_STATUS).findViewById(R.id.tv_withDrawNow).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //弹出开启权限
                        PermissionUtils.getInstance().showSystemPermissionsSettingDialog(PartCategoriesActivity.this);
                    }
                });
            }
        }

    }

    //获取位置信息
    private void getLocation() {
        pullToBothLayout.showView(ViewStatus.LOADING_STATUS);
        //获取城市编码
        GPSUtils.getInstance(this).getLocation(new myLocation() {
            @Override
            public void onSuccess(String cc) {
                //获取成功开始获取内容
                city = cc;
                getJobList2();
            }

            @Override
            public void onFail(int code) {
                //获取位置信息失败
                pullToBothLayout.showView(ViewStatus.EMPTY_STATUS);
            }
        });
    }

    @Override
    public void setTitleBarColor() {

    }

    @Override
    protected boolean isStatusBarBlack() {
        return true;
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_part_actegory;
    }

    @Override
    public void initView() {

        LinearLayoutManager manager = new LinearLayoutManager(this);
        if (dailyAdapter == null) {
            dailyAdapter = new PartApplyAdapter(PartCategoriesActivity.this, list);
        }
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        // 第一种，直接取消动画
        RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(dailyAdapter);
        dailyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //跳转兼职详情
                startActivity(new Intent(PartCategoriesActivity.this, PartDetailActivity.class).putExtra("jobId", list.get(position).getJobId()));
            }
        });

        tvList.add(tvLast);
        tvList.add(tvZq);
        tvList.add(tvHigh);
        tvList.add(tvNear);

        lineList.add(line_1);
        lineList.add(line_2);
        lineList.add(line_3);
        lineList.add(line_4);
        new TitleBuilder(this).setTitleText("")
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });

    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        assert type != null;
        switch (type) {
            case "0": //最新发布
                setVG(0);
                page = 1;
                type = "0";
                isLast = false;
                getJobList();
                break;
            case "1": //名气专场
                setVG(1);
                page = 1;
                type = "1";
                isLast = false;
                getJobList();
                break;
            case "2": //薪资最高
                setVG(2);
                page = 1;
                type = "2";
                isLast = false;
                getJobList();
                break;
            case "3": //离我最近
                setVG(3);
                page = 1;
                type = "3";
                isLast = true;
                getLocationPermission();
                break;

        }
    }

    //设置显示隐藏
    private void setVG(int position) {
        for (int i = 0; i < tvList.size(); i++) {
            if (i == position) {
                tvList.get(i).setTextColor(getResources().getColor(R.color.colorFE6B2F));
                lineList.get(i).setVisibility(View.VISIBLE);
            } else {
                tvList.get(i).setTextColor(getResources().getColor(R.color.color666));
                lineList.get(i).setVisibility(View.GONE);
            }
        }
    }

    @OnClick({R.id.ll_last, R.id.ll_zq, R.id.ll_high, R.id.ll_near})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.ll_last: //最新发布
                setVG(0);
                page = 1;
                type = "0";
                isLast = false;
                isRefresh = true;
                getJobList();
                break;
            case R.id.ll_zq: //名气专场
                setVG(1);
                page = 1;
                type = "1";
                isRefresh = true;
                isLast = false;
                getJobList();
                break;
            case R.id.ll_high: //薪资最高
                setVG(2);
                page = 1;
                type = "2";
                isRefresh = true;
                isLast = false;
                getJobList();
                break;
            case R.id.ll_near: //离我最近
                setVG(3);
                page = 1;
                type = "3";
                isRefresh = true;
                isLast = true;
                getLocationPermission();
                break;

        }
    }

    //获取列表信息
    private void getJobList2() {
        if (isRefresh)
            pullToBothLayout.showView(ViewStatus.LOADING_STATUS);
        NoValidationTask.getApiService().getRM2(type, page, city).enqueue(new MyCallback<PartBaseEntity>(PartCategoriesActivity.this) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                String jsonStr = JSONObject.toJSONString(response.body().getData());
                JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                if (isRefresh) {
                    list.clear();
                    if (jsonArray.size() > 0) {
                        pullToBothLayout.showView(ViewStatus.CONTENT_STATUS);
                        for (int i = 0; i < jsonArray.size(); i++) {
                            DailyEntity dailyEntity = new DailyEntity();
                            dailyEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            dailyEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            dailyEntity.setLabel(jsonArray.getJSONObject(i).getString("jobPayType"));
                            dailyEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            dailyEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            dailyEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            dailyEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            list.add(dailyEntity);
                        }

                    } else {
                        pullToBothLayout.showView(ViewStatus.EMPTY_STATUS);
                    }
                } else {
                    pullToBothLayout.showView(ViewStatus.CONTENT_STATUS);
                    if (jsonArray.size() > 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            DailyEntity dailyEntity = new DailyEntity();
                            dailyEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            dailyEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            dailyEntity.setLabel(jsonArray.getJSONObject(i).getString("jobPayType"));
                            dailyEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            dailyEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            dailyEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            dailyEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            list.add(dailyEntity);
                        }
                    }
                }
                dailyAdapter.notifyDataSetChanged();
                closePullTo();
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //获取列表信息
    private void getJobList() {
        if (isRefresh)
            pullToBothLayout.showView(ViewStatus.LOADING_STATUS);
        NoValidationTask.getApiService().getRM(type, page).enqueue(new MyCallback<PartBaseEntity>(PartCategoriesActivity.this) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                String jsonStr = JSONObject.toJSONString(response.body().getData());
                JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                if (isRefresh) {
                    list.clear();
                    if (jsonArray.size() > 0) {
                        pullToBothLayout.showView(ViewStatus.CONTENT_STATUS);
                        for (int i = 0; i < jsonArray.size(); i++) {
                            DailyEntity dailyEntity = new DailyEntity();
                            dailyEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            dailyEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            dailyEntity.setLabel(jsonArray.getJSONObject(i).getString("jobPayType"));
                            dailyEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            dailyEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            dailyEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            dailyEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            list.add(dailyEntity);
                        }

                    } else {
                        pullToBothLayout.showView(ViewStatus.EMPTY_STATUS);
                    }
                } else {
                    pullToBothLayout.showView(ViewStatus.CONTENT_STATUS);
                    if (jsonArray.size() > 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            DailyEntity dailyEntity = new DailyEntity();
                            dailyEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            dailyEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            dailyEntity.setLabel(jsonArray.getJSONObject(i).getString("jobPayType"));
                            dailyEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            dailyEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            dailyEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            dailyEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            list.add(dailyEntity);
                        }
                    }
                }
                dailyAdapter.notifyDataSetChanged();
                closePullTo();
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }
}
